<template>
  <div class="app-container">
    <el-card shadow="never">
      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
        <el-form-item label="参数名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入参数名称" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="参数键名" prop="key">
          <el-input v-model="queryParams.key" placeholder="请输入参数键名" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="参数分组" prop="group">
          <el-select v-model="queryParams.group" placeholder="请选择参数分组" clearable>
            <el-option v-for="item in groupOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="参数类型" prop="type">
          <dict-select v-model="queryParams.type" dict-type="sys_config_type" placeholder="请选择参数类型" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作区域 -->
      <el-row :gutter="10" class="mb-2">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:config:add']">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['system:config:edit']">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:config:delete']">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['system:config:export']">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="Refresh" @click="handleRefreshCache" v-hasPermi="['system:config:refreshCache']">刷新缓存</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="View" @click="toGroupView" v-hasPermi="['system:config:list']">分组视图</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!-- 数据表格 -->
      <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="参数ID" align="center" prop="id" width="80" />
        <el-table-column label="参数名称" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="参数键名" align="center" prop="key" :show-overflow-tooltip="true" />
        <el-table-column label="参数值" align="center" prop="value" :show-overflow-tooltip="true">
          <template #default="scope">
            <span v-if="scope.row.type === 'boolean'">
              {{ scope.row.value === 'true' ? '是' : '否' }}
            </span>
            <span v-else-if="scope.row.value && scope.row.value.length > 100">
              {{ scope.row.value.substring(0, 100) + '...' }}
            </span>
            <span v-else>{{ scope.row.value }}</span>
          </template>
        </el-table-column>
        <el-table-column label="参数分组" align="center" prop="group" />
        <el-table-column label="参数类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="typeOptions" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:config:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:config:delete']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.page"
        v-model:limit="queryParams.limit"
        @pagination="getList"
      />

      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" v-model="open" width="600px" append-to-body>
        <el-form ref="configForm" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="参数名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入参数名称" />
          </el-form-item>
          <el-form-item label="参数键名" prop="key">
            <el-input v-model="form.key" placeholder="请输入参数键名" />
          </el-form-item>
          <el-form-item label="参数分组" prop="group">
            <el-select v-model="form.group" placeholder="请选择参数分组" clearable>
              <el-option v-for="item in groupOptions" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="参数类型" prop="type">
            <dict-select v-model="form.type" dict-type="sys_config_type" placeholder="请选择参数类型" />
          </el-form-item>
          <el-form-item label="参数值" prop="value">
            <el-input v-if="form.type === 'string'" v-model="form.value" placeholder="请输入参数值" />
            <el-input-number v-else-if="form.type === 'number'" v-model="form.valueNum" :precision="0" :controls="true" style="width: 100%" />
            <el-switch v-else-if="form.type === 'boolean'" v-model="form.valueBool" />
            <el-input v-else-if="form.type === 'json'" v-model="form.value" type="textarea" :rows="5" placeholder="请输入JSON格式的参数值" />
            <el-input v-else v-model="form.value" placeholder="请输入参数值" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getConfigList, getConfigDetail, createConfig, updateConfig, deleteConfig, refreshConfigCache, exportConfig, getConfigGroups } from '@/api/config'
import { parseConfigValue } from '@/utils/config'
import { useRouter } from 'vue-router'

const router = useRouter()

// 列表数据
const configList = ref([])
const total = ref(0)
const loading = ref(false)
const single = ref(true)
const multiple = ref(true)
const ids = ref([])
const showSearch = ref(true)

// 查询参数
const queryParams = ref({
  page: 1,
  limit: 10,
  name: '',
  key: '',
  group: '',
  type: ''
})

// 表单参数
const open = ref(false)
const title = ref('')
const form = reactive({
  id: undefined,
  name: '',
  key: '',
  value: '',
  valueNum: 0,
  valueBool: false,
  group: '',
  type: 'string',
  remark: ''
})

// 表单校验规则
const rules = reactive({
  name: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
  key: [{ required: true, message: '参数键名不能为空', trigger: 'blur' }],
  value: [{ required: true, message: '参数值不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '参数类型不能为空', trigger: 'change' }]
})

// 参数类型选项
const typeOptions = ref([])
// 参数分组选项
const groupOptions = ref([])

// 监听参数类型变化，自动转换参数值
watch(() => form.type, (newVal, oldVal) => {
  if (newVal === 'number' && form.value) {
    form.valueNum = parseFloat(form.value) || 0
  } else if (newVal === 'boolean' && form.value) {
    form.valueBool = form.value === 'true' || form.value === '1'
  } else if (newVal === 'json' && oldVal === 'string' && form.value) {
    try {
      const jsonObj = JSON.parse(form.value)
      form.value = JSON.stringify(jsonObj, null, 2)
    } catch (e) {
      // 不是有效的JSON，保持原样
    }
  }
})

// 监听数值类型的值变化
watch(() => form.valueNum, (val) => {
  if (form.type === 'number') {
    form.value = val.toString()
  }
})

// 监听布尔类型的值变化
watch(() => form.valueBool, (val) => {
  if (form.type === 'boolean') {
    form.value = val.toString()
  }
})

// 查询参数列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getConfigList(queryParams.value)
    configList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取参数列表失败', error)
  } finally {
    loading.value = false
  }
}

// 获取参数分组列表
const getGroups = async () => {
  try {
    const res = await getConfigGroups()
    groupOptions.value = res.data || []
  } catch (error) {
    console.error('获取参数分组失败', error)
  }
}

// 查询按钮操作
const handleQuery = () => {
  queryParams.value.page = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.value = {
    page: 1,
    limit: 10,
    name: '',
    key: '',
    group: '',
    type: ''
  }
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加参数'
}

// 修改按钮操作
const handleUpdate = async (row) => {
  reset()
  const id = row?.id || ids.value[0]
  try {
    const res = await getConfigDetail(id)
    Object.assign(form, res.data)
    
    // 根据类型设置特定值
    if (form.type === 'number') {
      form.valueNum = parseFloat(form.value) || 0
    } else if (form.type === 'boolean') {
      form.valueBool = form.value === 'true' || form.value === '1'
    }
    
    open.value = true
    title.value = '修改参数'
  } catch (error) {
    console.error('获取参数详情失败', error)
  }
}

// 提交表单
const configForm = ref()
const submitForm = async () => {
  configForm.value.validate(async (valid) => {
    if (!valid) return
    
    // 根据类型处理参数值
    if (form.type === 'json') {
      try {
        // 验证JSON格式
        JSON.parse(form.value)
      } catch (e) {
        ElMessage.error('JSON格式不正确，请检查')
        return
      }
    }
    
    try {
      if (form.id) {
        await updateConfig(form.id, form)
        ElMessage.success('修改成功')
      } else {
        await createConfig(form)
        ElMessage.success('新增成功')
      }
      open.value = false
      getList()
    } catch (error) {
      console.error('保存参数失败', error)
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  const configIds = row?.id || ids.value
  ElMessageBox.confirm('确认删除选中的参数配置吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteConfig(configIds)
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除参数失败', error)
    }
  })
}

// 导出按钮操作
const handleExport = async () => {
  try {
    await exportConfig(queryParams.value)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出参数失败', error)
  }
}

// 跳转到分组视图
const toGroupView = () => {
  router.push('/system/config/group')
}

// 刷新缓存按钮操作
const handleRefreshCache = async () => {
  try {
    await refreshConfigCache()
    ElMessage.success('刷新缓存成功')
  } catch (error) {
    console.error('刷新缓存失败', error)
  }
}

// 取消按钮操作
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.name = ''
  form.key = ''
  form.value = ''
  form.valueNum = 0
  form.valueBool = false
  form.group = ''
  form.type = 'string'
  form.remark = ''
}

onMounted(() => {
  getList()
  getGroups()
})
</script> 